home *** CD-ROM | disk | FTP | other *** search
/ Scene Storm / Scene Storm - Volume 1.iso / coding / c / jpeglib5b / rdgif.c < prev    next >
C/C++ Source or Header  |  1980-01-12  |  23KB  |  682 lines

  1. /*
  2.  * rdgif.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  **************************************************************************
  9.  * WARNING: You will need an LZW patent license from Unisys in order to   *
  10.  * use this file legally in any commercial or shareware application.      *
  11.  **************************************************************************
  12.  *
  13.  * This file contains routines to read input images in GIF format.
  14.  *
  15.  * These routines may need modification for non-Unix environments or
  16.  * specialized applications.  As they stand, they assume input from
  17.  * an ordinary stdio stream.  They further assume that reading begins
  18.  * at the start of the file; input_init may need work if the
  19.  * user interface has already read some data (e.g., to determine that
  20.  * the file is indeed GIF format).
  21.  */
  22.  
  23. /*
  24.  * This code is loosely based on giftoppm from the PBMPLUS distribution
  25.  * of Feb. 1991.  That file contains the following copyright notice:
  26.  * +-------------------------------------------------------------------+
  27.  * | Copyright 1990, David Koblas.                                     |
  28.  * |   Permission to use, copy, modify, and distribute this software   |
  29.  * |   and its documentation for any purpose and without fee is hereby |
  30.  * |   granted, provided that the above copyright notice appear in all |
  31.  * |   copies and that both that copyright notice and this permission  |
  32.  * |   notice appear in supporting documentation.  This software is    |
  33.  * |   provided "as is" without express or implied warranty.           |
  34.  * +-------------------------------------------------------------------+
  35.  *
  36.  * We are also required to state that
  37.  *    "The Graphics Interchange Format(c) is the Copyright property of
  38.  *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
  39.  *    CompuServe Incorporated."
  40.  */
  41.  
  42. #include "cdjpeg.h"        /* Common decls for cjpeg/djpeg applications */
  43.  
  44. #ifdef GIF_SUPPORTED
  45.  
  46.  
  47. #define    MAXCOLORMAPSIZE    256    /* max # of colors in a GIF colormap */
  48. #define NUMCOLORS    3    /* # of colors */
  49. #define CM_RED        0    /* color component numbers */
  50. #define CM_GREEN    1
  51. #define CM_BLUE        2
  52.  
  53. #define    MAX_LZW_BITS    12    /* maximum LZW code size */
  54. #define LZW_TABLE_SIZE    (1<<MAX_LZW_BITS) /* # of possible LZW symbols */
  55.  
  56. /* Macros for extracting header data --- note we assume chars may be signed */
  57.  
  58. #define LM_to_uint(a,b)        ((((b)&0xFF) << 8) | ((a)&0xFF))
  59.  
  60. #define BitSet(byte, bit)    ((byte) & (bit))
  61. #define INTERLACE    0x40    /* mask for bit signifying interlaced image */
  62. #define COLORMAPFLAG    0x80    /* mask for bit signifying colormap presence */
  63.  
  64. #define    ReadOK(file,buffer,len)    (JFREAD(file,buffer,len) == ((size_t) (len)))
  65.  
  66. /* LZW decompression tables look like this:
  67.  *   symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  68.  *   symbol_tail[K] = suffix byte   of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  69.  * Note that entries 0..end_code of the above tables are not used,
  70.  * since those symbols represent raw bytes or special codes.
  71.  *
  72.  * The stack represents the not-yet-used expansion of the last LZW symbol.
  73.  * In the worst case, a symbol could expand to as many bytes as there are
  74.  * LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
  75.  * (This is conservative since that number includes the raw-byte symbols.)
  76.  *
  77.  * The tables are allocated from FAR heap space since they would use up
  78.  * rather a lot of the near data space in a PC.
  79.  */
  80.  
  81.  
  82. /* Private version of data source object */
  83.  
  84. typedef struct {
  85.   struct cjpeg_source_struct pub; /* public fields */
  86.  
  87.   j_compress_ptr cinfo;        /* back link saves passing separate parm */
  88.  
  89.   JSAMPARRAY colormap;        /* GIF colormap (converted to my format) */
  90.  
  91.   /* State for GetCode and LZWReadByte */
  92.   char code_buf[256+4];        /* current input data block */
  93.   int last_byte;        /* # of bytes in code_buf */
  94.   int last_bit;            /* # of bits in code_buf */
  95.   int cur_bit;            /* next bit index to read */
  96.   boolean out_of_blocks;    /* TRUE if hit terminator data block */
  97.  
  98.   int input_code_size;        /* codesize given in GIF file */
  99.   int clear_code,end_code;    /* values for Clear and End codes */
  100.  
  101.   int code_size;        /* current actual code size */
  102.   int limit_code;        /* 2^code_size */
  103.   int max_code;            /* first unused code value */
  104.   boolean first_time;        /* flags first call to LZWReadByte */
  105.  
  106.   /* Private state for LZWReadByte */
  107.   int oldcode;            /* previous LZW symbol */
  108.   int firstcode;        /* first byte of oldcode's expansion */
  109.  
  110.   /* LZW symbol table and expansion stack */
  111.   UINT16 FAR *symbol_head;    /* => table of prefix symbols */
  112.   UINT8  FAR *symbol_tail;    /* => table of suffix bytes */
  113.   UINT8  FAR *symbol_stack;    /* => stack for symbol expansions */
  114.   UINT8  FAR *sp;        /* stack pointer */
  115.  
  116.   /* State for interlaced image processing */
  117.   boolean is_interlaced;    /* TRUE if have interlaced image */
  118.   jvirt_sarray_ptr interlaced_image; /* full image in interlaced order */
  119.   JDIMENSION cur_row_number;    /* need to know actual row number */
  120.   JDIMENSION pass2_offset;    /* # of pixel rows in pass 1 */
  121.   JDIMENSION pass3_offset;    /* # of pixel rows in passes 1&2 */
  122.   JDIMENSION pass4_offset;    /* # of pixel rows in passes 1,2,3 */
  123. } gif_source_struct;
  124.  
  125. typedef gif_source_struct * gif_source_ptr;
  126.  
  127.  
  128. /* Forward declarations */
  129. METHODDEF JDIMENSION get_pixel_rows
  130.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  131. METHODDEF JDIMENSION load_interlaced_image
  132.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  133. METHODDEF JDIMENSION get_interlaced_row
  134.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  135.  
  136.  
  137. LOCAL int
  138. ReadByte (gif_source_ptr sinfo)
  139. /* Read next byte from GIF file */
  140. {
  141.   register FILE * infile = sinfo->pub.input_file;
  142.   int c;
  143.  
  144.   if ((c = getc(infile)) == EOF)
  145.     ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  146.   return c;
  147. }
  148.  
  149.  
  150. LOCAL int
  151. GetDataBlock (gif_source_ptr sinfo, char *buf)
  152. /* Read a GIF data block, which has a leading count byte */
  153. /* A zero-length block marks the end of a data block sequence */
  154. {
  155.   int count;
  156.  
  157.   count = ReadByte(sinfo);
  158.   if (count > 0) {
  159.     if (! ReadOK(sinfo->pub.input_file, buf, count))
  160.       ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  161.   }
  162.   return count;
  163. }
  164.  
  165.  
  166. LOCAL void
  167. SkipDataBlocks (gif_source_ptr sinfo)
  168. /* Skip a series of data blocks, until a block terminator is found */
  169. {
  170.   char buf[256];
  171.  
  172.   while (GetDataBlock(sinfo, buf) > 0)
  173.     /* skip */;
  174. }
  175.  
  176.  
  177. LOCAL void
  178. ReInitLZW (gif_source_ptr sinfo)
  179. /* (Re)initialize LZW state; shared code for startup and Clear processing */
  180. {
  181.   sinfo->code_size = sinfo->input_code_size + 1;
  182.   sinfo->limit_code = sinfo->clear_code << 1;    /* 2^code_size */
  183.   sinfo->max_code = sinfo->clear_code + 2;    /* first unused code value */
  184.   sinfo->sp = sinfo->symbol_stack;        /* init stack to empty */
  185. }
  186.  
  187.  
  188. LOCAL void
  189. InitLZWCode (gif_source_ptr sinfo)
  190. /* Initialize for a series of LZWReadByte (and hence GetCode) calls */
  191. {
  192.   /* GetCode initialization */
  193.   sinfo->last_byte = 2;        /* make safe to "recopy last two bytes" */
  194.   sinfo->last_bit = 0;        /* nothing in the buffer */
  195.   sinfo->cur_bit = 0;        /* force buffer load on first call */
  196.   sinfo->out_of_blocks = FALSE;
  197.  
  198.   /* LZWReadByte initialization: */
  199.   /* compute special code values (note that these do not change later) */
  200.   sinfo->clear_code = 1 << sinfo->input_code_size;
  201.   sinfo->end_code = sinfo->clear_code + 1;
  202.   sinfo->first_time = TRUE;
  203.   ReInitLZW(sinfo);
  204. }
  205.  
  206.  
  207. LOCAL int
  208. GetCode (gif_source_ptr sinfo)
  209. /* Fetch the next code_size bits from the GIF data */
  210. /* We assume code_size is less than 16 */
  211. {
  212.   register INT32 accum;
  213.   int offs, ret, count;
  214.  
  215.   while ( (sinfo->cur_bit + sinfo->code_size) > sinfo->last_bit) {
  216.     /* Time to reload the buffer */
  217.     if (sinfo->out_of_blocks) {
  218.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  219.       return sinfo->end_code;    /* fake something useful */
  220.     }
  221.     /* preserve last two bytes of what we have -- assume code_size <= 16 */
  222.     sinfo->code_buf[0] = sinfo->code_buf[sinfo->last_byte-2];
  223.     sinfo->code_buf[1] = sinfo->code_buf[sinfo->last_byte-1];
  224.     /* Load more bytes; set flag if we reach the terminator block */
  225.     if ((count = GetDataBlock(sinfo, &sinfo->code_buf[2])) == 0) {
  226.       sinfo->out_of_blocks = TRUE;
  227.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  228.       return sinfo->end_code;    /* fake something useful */
  229.     }
  230.     /* Reset counters */
  231.     sinfo->cur_bit = (sinfo->cur_bit - sinfo->last_bit) + 16;
  232.     sinfo->last_byte = 2 + count;
  233.     sinfo->last_bit = sinfo->last_byte * 8;
  234.   }
  235.  
  236.   /* Form up next 24 bits in accum */
  237.   offs = sinfo->cur_bit >> 3;    /* byte containing cur_bit */
  238. #ifdef CHAR_IS_UNSIGNED
  239.   accum = sinfo->code_buf[offs+2];
  240.   accum <<= 8;
  241.   accum |= sinfo->code_buf[offs+1];
  242.   accum <<= 8;
  243.   accum |= sinfo->code_buf[offs];
  244. #else
  245.   accum = sinfo->code_buf[offs+2] & 0xFF;
  246.   accum <<= 8;
  247.   accum |= sinfo->code_buf[offs+1] & 0xFF;
  248.   accum <<= 8;
  249.   accum |= sinfo->code_buf[offs] & 0xFF;
  250. #endif
  251.  
  252.   /* Right-align cur_bit in accum, then mask off desired number of bits */
  253.   accum >>= (sinfo->cur_bit & 7);
  254.   ret = ((int) accum) & ((1 << sinfo->code_size) - 1);
  255.   
  256.   sinfo->cur_bit += sinfo->code_size;
  257.   return ret;
  258. }
  259.  
  260.  
  261. LOCAL int
  262. LZWReadByte (gif_source_ptr sinfo)
  263. /* Read an LZW-compressed byte */
  264. {
  265.   register int code;        /* current working code */
  266.   int incode;            /* saves actual input code */
  267.  
  268.   /* First time, just eat the expected Clear code(s) and return next code, */
  269.   /* which is expected to be a raw byte. */
  270.   if (sinfo->first_time) {
  271.     sinfo->first_time = FALSE;
  272.     code = sinfo->clear_code;    /* enables sharing code with Clear case */
  273.   } else {
  274.  
  275.     /* If any codes are stacked from a previously read symbol, return them */
  276.     if (sinfo->sp > sinfo->symbol_stack)
  277.       return (int) *(-- sinfo->sp);
  278.  
  279.     /* Time to read a new symbol */
  280.     code = GetCode(sinfo);
  281.  
  282.   }
  283.  
  284.   if (code == sinfo->clear_code) {
  285.     /* Reinit state, swallow any extra Clear codes, and */
  286.     /* return next code, which is expected to be a raw byte. */
  287.     ReInitLZW(sinfo);
  288.     do {
  289.       code = GetCode(sinfo);
  290.     } while (code == sinfo->clear_code);
  291.     if (code > sinfo->clear_code) { /* make sure it is a raw byte */
  292.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  293.       code = 0;            /* use something valid */
  294.     }
  295.     /* make firstcode, oldcode valid! */
  296.     sinfo->firstcode = sinfo->oldcode = code;
  297.     return code;
  298.   }
  299.  
  300.   if (code == sinfo->end_code) {
  301.     /* Skip the rest of the image, unless GetCode already read terminator */
  302.     if (! sinfo->out_of_blocks) {
  303.       SkipDataBlocks(sinfo);
  304.       sinfo->out_of_blocks = TRUE;
  305.     }
  306.     /* Complain that there's not enough data */
  307.     WARNMS(sinfo->cinfo, JWRN_GIF_ENDCODE);
  308.     /* Pad data with 0's */
  309.     return 0;            /* fake something usable */
  310.   }
  311.  
  312.   /* Got normal raw byte or LZW symbol */
  313.   incode = code;        /* save for a moment */
  314.   
  315.   if (code >= sinfo->max_code) { /* special case for not-yet-defined symbol */
  316.     /* code == max_code is OK; anything bigger is bad data */
  317.     if (code > sinfo->max_code) {
  318.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  319.       incode = 0;        /* prevent creation of loops in symbol table */
  320.     }
  321.     /* this symbol will be defined as oldcode/firstcode */
  322.     *(sinfo->sp++) = (UINT8) sinfo->firstcode;
  323.     code = sinfo->oldcode;
  324.   }
  325.  
  326.   /* If it's a symbol, expand it into the stack */
  327.   while (code >= sinfo->clear_code) {
  328.     *(sinfo->sp++) = sinfo->symbol_tail[code]; /* tail is a byte value */
  329.     code = sinfo->symbol_head[code]; /* head is another LZW symbol */
  330.   }
  331.   /* At this point code just represents a raw byte */
  332.   sinfo->firstcode = code;    /* save for possible future use */
  333.  
  334.   /* If there's room in table, */
  335.   if ((code = sinfo->max_code) < LZW_TABLE_SIZE) {
  336.     /* Define a new symbol = prev sym + head of this sym's expansion */
  337.     sinfo->symbol_head[code] = sinfo->oldcode;
  338.     sinfo->symbol_tail[code] = (UINT8) sinfo->firstcode;
  339.     sinfo->max_code++;
  340.     /* Is it time to increase code_size? */
  341.     if ((sinfo->max_code >= sinfo->limit_code) &&
  342.     (sinfo->code_size < MAX_LZW_BITS)) {
  343.       sinfo->code_size++;
  344.       sinfo->limit_code <<= 1;    /* keep equal to 2^code_size */
  345.     }
  346.   }
  347.   
  348.   sinfo->oldcode = incode;    /* save last input symbol for future use */
  349.   return sinfo->firstcode;    /* return first byte of symbol's expansion */
  350. }
  351.  
  352.  
  353. LOCAL void
  354. ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap)
  355. /* Read a GIF colormap */
  356. {
  357.   int i;
  358.  
  359.   for (i = 0; i < cmaplen; i++) {
  360. #if BITS_IN_JSAMPLE == 8
  361. #define UPSCALE(x)  (x)
  362. #else
  363. #define UPSCALE(x)  ((x) << (BITS_IN_JSAMPLE-8))
  364. #endif
  365.     cmap[CM_RED][i]   = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  366.     cmap[CM_GREEN][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  367.     cmap[CM_BLUE][i]  = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  368.   }
  369. }
  370.  
  371.  
  372. LOCAL void
  373. DoExtension (gif_source_ptr sinfo)
  374. /* Process an extension block */
  375. /* Currently we ignore 'em all */
  376. {
  377.   int extlabel;
  378.  
  379.   /* Read extension label byte */
  380.   extlabel = ReadByte(sinfo);
  381.   TRACEMS1(sinfo->cinfo, 1, JTRC_GIF_EXTENSION, extlabel);
  382.   /* Skip the data block(s) associated with the extension */
  383.   SkipDataBlocks(sinfo);
  384. }
  385.  
  386.  
  387. /*
  388.  * Read the file header; return image size and component count.
  389.  */
  390.  
  391. METHODDEF void
  392. start_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  393. {
  394.   gif_source_ptr source = (gif_source_ptr) sinfo;
  395.   char hdrbuf[10];        /* workspace for reading control blocks */
  396.   unsigned int width, height;    /* image dimensions */
  397.   int colormaplen, aspectRatio;
  398.   int c;
  399.  
  400.   /* Allocate space to store the colormap */
  401.   source->colormap = (*cinfo->mem->alloc_sarray)
  402.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  403.      (JDIMENSION) MAXCOLORMAPSIZE, (JDIMENSION) NUMCOLORS);
  404.  
  405.   /* Read and verify GIF Header */
  406.   if (! ReadOK(source->pub.input_file, hdrbuf, 6))
  407.     ERREXIT(cinfo, JERR_GIF_NOT);
  408.   if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')
  409.     ERREXIT(cinfo, JERR_GIF_NOT);
  410.   /* Check for expected version numbers.
  411.    * If unknown version, give warning and try to process anyway;
  412.    * this is per recommendation in GIF89a standard.
  413.    */
  414.   if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&
  415.       (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))
  416.     TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);
  417.  
  418.   /* Read and decipher Logical Screen Descriptor */
  419.   if (! ReadOK(source->pub.input_file, hdrbuf, 7))
  420.     ERREXIT(cinfo, JERR_INPUT_EOF);
  421.   width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
  422.   height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
  423.   colormaplen = 2 << (hdrbuf[4] & 0x07);
  424.   /* we ignore the color resolution, sort flag, and background color index */
  425.   aspectRatio = hdrbuf[6] & 0xFF;
  426.   if (aspectRatio != 0 && aspectRatio != 49)
  427.     TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);
  428.  
  429.   /* Read global colormap if header indicates it is present */
  430.   if (BitSet(hdrbuf[4], COLORMAPFLAG))
  431.     ReadColorMap(source, colormaplen, source->colormap);
  432.  
  433.   /* Scan until we reach start of desired image.
  434.    * We don't currently support skipping images, but could add it easily.
  435.    */
  436.   for (;;) {
  437.     c = ReadByte(source);
  438.  
  439.     if (c == ';')        /* GIF terminator?? */
  440.       ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);
  441.  
  442.     if (c == '!') {        /* Extension */
  443.       DoExtension(source);
  444.       continue;
  445.     }
  446.     
  447.     if (c != ',') {        /* Not an image separator? */
  448.       WARNMS1(cinfo, JWRN_GIF_CHAR, c);
  449.       continue;
  450.     }
  451.  
  452.     /* Read and decipher Local Image Descriptor */
  453.     if (! ReadOK(source->pub.input_file, hdrbuf, 9))
  454.       ERREXIT(cinfo, JERR_INPUT_EOF);
  455.     /* we ignore top/left position info, also sort flag */
  456.     width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
  457.     height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
  458.     source->is_interlaced = BitSet(hdrbuf[8], INTERLACE);
  459.  
  460.     /* Read local colormap if header indicates it is present */
  461.     /* Note: if we wanted to support skipping images, */
  462.     /* we'd need to skip rather than read colormap for ignored images */
  463.     if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
  464.       colormaplen = 2 << (hdrbuf[8] & 0x07);
  465.       ReadColorMap(source, colormaplen, source->colormap);
  466.     }
  467.  
  468.     source->input_code_size = ReadByte(source); /* get min-code-size byte */
  469.     if (source->input_code_size < 2 || source->input_code_size >= MAX_LZW_BITS)
  470.       ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);
  471.  
  472.     /* Reached desired image, so break out of loop */
  473.     /* If we wanted to skip this image, */
  474.     /* we'd call SkipDataBlocks and then continue the loop */
  475.     break;
  476.   }
  477.  
  478.   /* Prepare to read selected image: first initialize LZW decompressor */
  479.   source->symbol_head = (UINT16 FAR *)
  480.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  481.                 LZW_TABLE_SIZE * SIZEOF(UINT16));
  482.   source->symbol_tail = (UINT8 FAR *)
  483.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  484.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  485.   source->symbol_stack = (UINT8 FAR *)
  486.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  487.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  488.   InitLZWCode(source);
  489.  
  490.   /*
  491.    * If image is interlaced, we read it into a full-size sample array,
  492.    * decompressing as we go; then get_interlaced_row selects rows from the
  493.    * sample array in the proper order.
  494.    */
  495.   if (source->is_interlaced) {
  496.     /* We request the virtual array now, but can't access it until virtual
  497.      * arrays have been allocated.  Hence, the actual work of reading the
  498.      * image is postponed until the first call to get_pixel_rows.
  499.      */
  500.     source->interlaced_image = (*cinfo->mem->request_virt_sarray)
  501.       ((j_common_ptr) cinfo, JPOOL_IMAGE,
  502.        (JDIMENSION) width, (JDIMENSION) height, (JDIMENSION) 1);
  503.     if (cinfo->progress != NULL) {
  504.       cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  505.       progress->total_extra_passes++; /* count file input as separate pass */
  506.     }
  507.     source->pub.get_pixel_rows = load_interlaced_image;
  508.   } else {
  509.     source->pub.get_pixel_rows = get_pixel_rows;
  510.   }
  511.  
  512.   /* Create compressor input buffer. */
  513.   source->pub.buffer = (*cinfo->mem->alloc_sarray)
  514.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  515.      (JDIMENSION) width * NUMCOLORS, (JDIMENSION) 1);
  516.   source->pub.buffer_height = 1;
  517.  
  518.   /* Return info about the image. */
  519.   cinfo->in_color_space = JCS_RGB;
  520.   cinfo->input_components = NUMCOLORS;
  521.   cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
  522.   cinfo->image_width = width;
  523.   cinfo->image_height = height;
  524.  
  525.   TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
  526. }
  527.  
  528.  
  529. /*
  530.  * Read one row of pixels.
  531.  * This version is used for noninterlaced GIF images:
  532.  * we read directly from the GIF file.
  533.  */
  534.  
  535. METHODDEF JDIMENSION
  536. get_pixel_rows (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  537. {
  538.   gif_source_ptr source = (gif_source_ptr) sinfo;
  539.   register int c;
  540.   register JSAMPROW ptr;
  541.   register JDIMENSION col;
  542.   register JSAMPARRAY colormap = source->colormap;
  543.   
  544.   ptr = source->pub.buffer[0];
  545.   for (col = cinfo->image_width; col > 0; col--) {
  546.     c = LZWReadByte(source);
  547.     *ptr++ = colormap[CM_RED][c];
  548.     *ptr++ = colormap[CM_GREEN][c];
  549.     *ptr++ = colormap[CM_BLUE][c];
  550.   }
  551.   return 1;
  552. }
  553.  
  554.  
  555. /*
  556.  * Read one row of pixels.
  557.  * This version is used for the first call on get_pixel_rows when
  558.  * reading an interlaced GIF file: we read the whole image into memory.
  559.  */
  560.  
  561. METHODDEF JDIMENSION
  562. load_interlaced_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  563. {
  564.   gif_source_ptr source = (gif_source_ptr) sinfo;
  565.   JSAMPARRAY image_ptr;
  566.   register JSAMPROW sptr;
  567.   register JDIMENSION col;
  568.   JDIMENSION row;
  569.   cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  570.  
  571.   /* Read the interlaced image into the virtual array we've created. */
  572.   for (row = 0; row < cinfo->image_height; row++) {
  573.     if (progress != NULL) {
  574.       progress->pub.pass_counter = (long) row;
  575.       progress->pub.pass_limit = (long) cinfo->image_height;
  576.       (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
  577.     }
  578.     image_ptr = (*cinfo->mem->access_virt_sarray)
  579.       ((j_common_ptr) cinfo, source->interlaced_image, row, TRUE);
  580.     sptr = image_ptr[0];
  581.     for (col = cinfo->image_width; col > 0; col--) {
  582.       *sptr++ = (JSAMPLE) LZWReadByte(source);
  583.     }
  584.   }
  585.   if (progress != NULL)
  586.     progress->completed_extra_passes++;
  587.  
  588.   /* Replace method pointer so subsequent calls don't come here. */
  589.   source->pub.get_pixel_rows = get_interlaced_row;
  590.   /* Initialize for get_interlaced_row, and perform first call on it. */
  591.   source->cur_row_number = 0;
  592.   source->pass2_offset = (cinfo->image_height + 7) / 8;
  593.   source->pass3_offset = source->pass2_offset + (cinfo->image_height + 3) / 8;
  594.   source->pass4_offset = source->pass3_offset + (cinfo->image_height + 1) / 4;
  595.  
  596.   return get_interlaced_row(cinfo, sinfo);
  597. }
  598.  
  599.  
  600. /*
  601.  * Read one row of pixels.
  602.  * This version is used for interlaced GIF images:
  603.  * we read from the virtual array.
  604.  */
  605.  
  606. METHODDEF JDIMENSION
  607. get_interlaced_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  608. {
  609.   gif_source_ptr source = (gif_source_ptr) sinfo;
  610.   JSAMPARRAY image_ptr;
  611.   register int c;
  612.   register JSAMPROW sptr, ptr;
  613.   register JDIMENSION col;
  614.   register JSAMPARRAY colormap = source->colormap;
  615.   JDIMENSION irow;
  616.  
  617.   /* Figure out which row of interlaced image is needed, and access it. */
  618.   switch ((int) (source->cur_row_number & 7)) {
  619.   case 0:            /* first-pass row */
  620.     irow = source->cur_row_number >> 3;
  621.     break;
  622.   case 4:            /* second-pass row */
  623.     irow = (source->cur_row_number >> 3) + source->pass2_offset;
  624.     break;
  625.   case 2:            /* third-pass row */
  626.   case 6:
  627.     irow = (source->cur_row_number >> 2) + source->pass3_offset;
  628.     break;
  629.   default:            /* fourth-pass row */
  630.     irow = (source->cur_row_number >> 1) + source->pass4_offset;
  631.     break;
  632.   }
  633.   image_ptr = (*cinfo->mem->access_virt_sarray)
  634.     ((j_common_ptr) cinfo, source->interlaced_image, irow, FALSE);
  635.   /* Scan the row, expand colormap, and output */
  636.   sptr = image_ptr[0];
  637.   ptr = source->pub.buffer[0];
  638.   for (col = cinfo->image_width; col > 0; col--) {
  639.     c = GETJSAMPLE(*sptr++);
  640.     *ptr++ = colormap[CM_RED][c];
  641.     *ptr++ = colormap[CM_GREEN][c];
  642.     *ptr++ = colormap[CM_BLUE][c];
  643.   }
  644.   source->cur_row_number++;    /* for next time */
  645.   return 1;
  646. }
  647.  
  648.  
  649. /*
  650.  * Finish up at the end of the file.
  651.  */
  652.  
  653. METHODDEF void
  654. finish_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  655. {
  656.   /* no work */
  657. }
  658.  
  659.  
  660. /*
  661.  * The module selection routine for GIF format input.
  662.  */
  663.  
  664. GLOBAL cjpeg_source_ptr
  665. jinit_read_gif (j_compress_ptr cinfo)
  666. {
  667.   gif_source_ptr source;
  668.  
  669.   /* Create module interface object */
  670.   source = (gif_source_ptr)
  671.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  672.                   SIZEOF(gif_source_struct));
  673.   source->cinfo = cinfo;    /* make back link for subroutines */
  674.   /* Fill in method ptrs, except get_pixel_rows which start_input sets */
  675.   source->pub.start_input = start_input_gif;
  676.   source->pub.finish_input = finish_input_gif;
  677.  
  678.   return (cjpeg_source_ptr) source;
  679. }
  680.  
  681. #endif /* GIF_SUPPORTED */
  682.